package com.personal.cuncunxing.module.home.recommend;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.personal.cuncunxing.R;
import com.personal.cuncunxing.common.OkHttpUtils;
import com.personal.cuncunxing.common.ResultCallback;
import com.personal.cuncunxing.common.StaticFiled;
import com.personal.cuncunxing.module.home.BaseFragment;
import com.personal.cuncunxing.module.home.pojo.ContactBeanConvert;
import com.personal.cuncunxing.module.home.pojo.Movie;
import com.personal.cuncunxing.module.player.PlayerActivity;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Request;

/**
 * Description:
 * Created by kode on 2020/5/26.
 */
public class RecommendFragment extends BaseFragment {
    private static final String TAG = "RecommendFragment";
    private RecyclerView recycler_view;
    private RecommendRVAdapter recommendRVAdapter;
    private ViewPager viewPager;
    private List<List<Movie>> listList;

    public RecommendFragment(ViewPager viewPager) {
        this.viewPager = viewPager;
    }

    @Override
    protected int setLayout() {
        return R.layout.home_recommand_fragment;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        recycler_view = view.findViewById(R.id.recommend_rv);
        //设置线性布局，默认垂直
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        recycler_view.setLayoutManager(layoutManager);
        //设置适配器
        recommendRVAdapter = new RecommendRVAdapter(getContext());
        recycler_view.setAdapter(recommendRVAdapter);
        setViewPager();
        isViewCreated = true;
        lazyLoad();
    }

    private void listenClick() {
        recommendRVAdapter.setOnSubItemClick(new RecommendSubRVAdapter.OnItemClick() {
            @Override
            public void OnItemClick(List<String> playUrl) {
                Intent intent = new Intent(getActivity(), PlayerActivity.class);
                intent.putExtra("playUrl",playUrl.get(0));
                startActivity(intent);
            }
        });
    }

    public void setListList(List<List<Movie>> listList) {
        //this.listList = listList;
        recommendRVAdapter.setListList(listList);
    }

    public void updateUI() {
        recommendRVAdapter.updateUI();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        Log.d(TAG, "setUserVisibleHint: ->" + isVisibleToUser);
        if (isVisibleToUser) {
            isUIVisible = true;
            lazyLoad();
        } else {
            isUIVisible = false;
        }
    }

    //懒加载
    @Override
    protected void lazyLoad() {
        // //这里进行双重标记判断,是因为setUserVisibleHint会多次回调,并且会在onCreateView执行前回调,
        // 必须确保onCreateView加载完毕且页面可见,才加载数据
        if (isViewCreated && isUIVisible) {
            loadData();
            //数据加载完毕,恢复标记,防止重复加载
            isViewCreated = false;
            isUIVisible = false;
            Log.d(TAG, "lazyLoad:->加载数据");
        }
    }

    /**
     * 加载数据
     */
    private void loadData() {
        //爬取电影资源
        OkHttpUtils.getInstance(getContext()).getAsyncHttp(StaticFiled.JSOUP_HOST, new ResultCallback() {
            @Override
            public void onError(Request request, Exception e) {

            }

            @Override
            public void onResponse(String str) throws IOException {
                List<List<Movie>> lists = new ArrayList<>();
                List<List<Movie>> list2s = new ArrayList<>();
                Document document = Jsoup.parse(str);
                Elements elements = document
                        .select("div[class=ui-ranking]")
                        .select("ul[class=ranking-list]");
                //Log.d(TAG, "onResponse: " + elements);
                for (final Element element : elements) {
                    final List<Movie> moviesList = new ArrayList<>();
                    final Elements element1s = element.select("li");
                    for (final Element element1 : element1s) {
                        final Movie movies = new Movie();
                        //标题
                        movies.setTitle(element1.select("a").text());
                        //下一级页面链接
                        movies.setUrl(element1.select("a").attr("href"));
                        //评分
                        movies.setScore(element1.select("span").text());
                        moviesList.add(movies);
                    }
                    lists.add(moviesList);
                }
                Log.d(TAG, "onResponse: "+ ContactBeanConvert.getInstance().convertToDatabaseValue(lists));
                list2s.add(lists.get(1));
                list2s.add(lists.get(0));
                list2s.add(lists.get(2));
                if (list2s.size() != 0) {
                    setListList(list2s);
                    updateUI();
                }
            }
        });
    }

    /**
     * 点击查看更多
     * 跳转到对应的viewpager
     */
    public void setViewPager() {
        recommendRVAdapter.setOnItemClick(new RecommendRVAdapter.OnItemClick() {
            @Override
            public void onItemClick(int position) {
                viewPager.setCurrentItem(position);
            }
        });
    }
}
